/**
 * Copyright © 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.basicdata.basicunit.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.basicdata.basicunit.entity.BasicUnit;
import com.jeeplus.modules.basicdata.basicunit.mapper.BasicUnitMapper;
import com.jeeplus.modules.basicdata.basicunit.entity.BasicUnitDepart;
import com.jeeplus.modules.basicdata.basicunit.mapper.BasicUnitDepartMapper;

/**
 * 基础单位信息Service
 * @author 刘明星
 * @version 2021-11-18
 */
@Service
@Transactional(readOnly = true)
public class BasicUnitService extends CrudService<BasicUnitMapper, BasicUnit> {

	@Autowired
	private BasicUnitDepartMapper basicUnitDepartMapper;

	public BasicUnit get(String id) {
		BasicUnit basicUnit = super.get(id);
		basicUnit.setBasicUnitDepartList(basicUnitDepartMapper.findList(new BasicUnitDepart(basicUnit)));
		return basicUnit;
	}

	public List<BasicUnit> findList(BasicUnit basicUnit) {
		return super.findList(basicUnit);
	}

	public Page<BasicUnit> findPage(Page<BasicUnit> page, BasicUnit basicUnit) {
		return super.findPage(page, basicUnit);
	}

	@Transactional(readOnly = false)
	public void save(BasicUnit basicUnit) {
		super.save(basicUnit);
		for (BasicUnitDepart basicUnitDepart : basicUnit.getBasicUnitDepartList()){
			if (basicUnitDepart.getId() == null){
				continue;
			}
			if (BasicUnitDepart.DEL_FLAG_NORMAL.equals(basicUnitDepart.getDelFlag())){
				if (StringUtils.isBlank(basicUnitDepart.getId())){
					basicUnitDepart.setUnit(basicUnit);
					basicUnitDepart.preInsert();
					basicUnitDepartMapper.insert(basicUnitDepart);
				}else{
					basicUnitDepart.preUpdate();
					basicUnitDepartMapper.update(basicUnitDepart);
				}
			}else{
				basicUnitDepartMapper.delete(basicUnitDepart);
			}
		}
	}

	@Transactional(readOnly = false)
	public void delete(BasicUnit basicUnit) {
		super.delete(basicUnit);
		basicUnitDepartMapper.delete(new BasicUnitDepart(basicUnit));
	}

}